package com.denlaku.longan.service.impl;

import com.denlaku.longan.service.DictionaryService;
import com.denlaku.longan.vo.LexiconItem;
import org.apache.commons.collections4.ListUtils;
import org.lionsoul.jcseg.IWord;
import org.lionsoul.jcseg.dic.ADictionary;
import org.lionsoul.jcseg.dic.DictionaryFactory;
import org.lionsoul.jcseg.dic.ILexicon;
import org.lionsoul.jcseg.segmenter.SegmenterConfig;
import org.lionsoul.jcseg.segmenter.Word;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author tianx
 */
@Service
public class DictionaryServiceImpl implements DictionaryService {
    private final ConcurrentMap<String, ADictionary> dictionaryMap = new ConcurrentHashMap<>();

    @Override
    public ADictionary getOrInitDictionary(String namespace) {
        ADictionary dictionary = dictionaryMap.get(namespace);
        if (dictionary != null) {
            return dictionary;
        }
        return dictionaryMap.computeIfAbsent(namespace,
                key -> DictionaryFactory.createDefaultDictionary(new SegmenterConfig()));
    }

    @Override
    public void loadLexiconItems(String namespace, List<LexiconItem> lexiconItems) {
        ADictionary dictionary = this.getOrInitDictionary(namespace);
        for (LexiconItem lexiconItem : ListUtils.emptyIfNull(lexiconItems)) {
            String text = lexiconItem.getText();
            IWord word = new Word(text, ILexicon.CJK_WORD);
            dictionary.add(ILexicon.CJK_WORD, word);
        }
    }
}
